#!/usr/bin/perl
use strict;
use warnings;
use FindBin qw($Bin);
use lib "$Bin";

use MDBCWSandbox;
use MDBAWS;
use MDBUtils;

my $queue  = MDBAWS::sqs_get_queue("cwsandbox");
my $config = MDBUtils::get_config();
my $result;

while (1) {
    my $msg = MDBAWS::sqs_get_message($queue);

    if ( !defined($msg) ) {
        print "DEBUG: No tickets in the queue, quiting...\n";
        exit(0);
    }
    else {
        my $metadata = MDBAWS::sdb_get_metadata( $msg->MessageBody() );
        my $cw_metadata;

        if ( defined( $metadata->{'sha256'} ) ) {
            $cw_metadata->{'sha256'} = $metadata->{'sha256'};

            if ( !defined( $metadata->{'cwsandbox_detailspage'} ) ) {
                my $file =
                  MDBAWS::s3_get_file( $config->{'aws'}->{'bucketname'},
                    $metadata->{'zipname'} );

                $cw_metadata->{'cwsandbox_detailspage'} =
                  MDBCWSandbox::CWSubmitSample($file);
                unlink($file);
            }

            if ( !defined( $metadata->{'cwsandbox_reportpage'} )
                && defined( $cw_metadata->{'cwsandbox_detailspage'} ) )
            {
                $cw_metadata->{'cwsandbox_reportpage'} =
                  MDBCWSandbox::GetCWXMLReportURL(
                    $cw_metadata->{'cwsandbox_detailspage'} );

                MDBAWS::sqs_put_queue( "cwsandbox", $msg->MessageBody() );
            }
            if (   defined( $cw_metadata->{'cwsandbox_detailspage'} )
                || defined( $cw_metadata->{'cwsandbox_reportpage'} ) )
            {
                MDBAWS::sdb_put_metadata($cw_metadata);
            }
        }
        $queue->DeleteMessage( $msg->ReceiptHandle() );
    }
}
